# encoding: utf-8
from __future__ import unicode_literals

from datetime import timedelta, datetime


def datetime_offset_by_month(datetime1, n=1):
    one_day = timedelta(days=1)
    q, r = divmod(datetime1.month + n, 12)
    datetime2 = datetime(datetime1.year + q, r + 1, 1) - one_day
    if datetime1.month != (datetime1 + one_day).month:
        return datetime2
    if datetime1.day >= datetime2.day:
        return datetime2
    return datetime2.replace(day=datetime1.day)


def day_of_month(currday=datetime.now()):
    month = currday.month
    year = currday.year
    d1 = datetime(year, month, 1)
    if month == 12:
        d2 = datetime(year + 1, 1, 1)
    else:
        d2 = datetime(year, month + 1, 1)
    return (d2 - d1).days


def monthdays(currday=datetime.now()):
    month = currday.month
    year = currday.year
    d1 = datetime(year, month, 1)
    if month == 12:
        d2 = datetime(year + 1, 1, 1)
    else:
        d2 = datetime(year, month + 1, 1)
    return d1, d1.replace(day=(d2 - d1).days)


def monthday(currday=datetime.now()):
    month = currday.month
    year = currday.year
    d1 = datetime(year, month, 1)
    if month == 12:
        d2 = datetime(year + 1, 1, 1)
        d3 = datetime(year + 1, 2, 1)
    else:
        d2 = datetime(year, month + 1, 1)
        if month == 11:
            d3 = datetime(year + 1, 1, 1)
        else:
            d3 = datetime(year, month + 2, 1)

    return datetime.strftime(d1, '%Y-%m-%d'), datetime.strftime(d2, '%Y-%m-%d'), datetime.strftime(d3, '%Y-%m-%d')


def weekday(currday=datetime.now()):
    year = currday.year  # datetime.strftime(currday, '%Y')
    week = datetime.strftime(currday, '%W')

    weekstart = datetime.strptime('%s-%s-1' % (year, week), '%Y-%W-%w')
    weekend = datetime.strptime('%s-%s-0' % (year, week), '%Y-%W-%w')
    return [weekstart, weekend]


def group_by(query_set, group_by):
    """util:django 获取分类列表"""
    from django.db.models import Count, QuerySet
    assert isinstance(query_set, QuerySet)
    django_groups = query_set.values(group_by).annotate(Count(group_by))
    groups = []
    for dict_ in django_groups:
        groups.append(dict_.get(group_by))
    return groups
